/*
 * @Author: wangjun haodreams@163.com
 * @Date: 2024-07-05 18:25:31
 * @LastEditors: wangjun haodreams@163.com
 * @LastEditTime: 2024-07-09 11:21:27
 * @FilePath: \golib\pdflite\pdflite.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package xpdf

import (
	"image/color"

	"gitee.com/haodreams/golib/xfont"

	"github.com/signintech/gopdf"
)

type PdfX struct {
	pdfHight  float64 //= 820.0 //pdf 内容的高度
	pdfTop    float64 //= 20.0  //pdf 第一行的位置
	defHeight float64 //= 0
	*gopdf.GoPdf
}

func NewPdfX(font *xfont.Font, config *gopdf.Config) *PdfX {
	m := new(PdfX)
	m.GoPdf = &gopdf.GoPdf{}
	m.Start(*config)
	m.AddTTFFontData(font.Name(), font.FontData())
	m.SetFont(font.Name(), "", font.Size()) //设置默认字体
	m.AddPage()
	m.defHeight = float64(font.Height())
	m.pdfHight = 820
	m.pdfTop = 20
	return m
}

func (m *PdfX) SetHeight(h float64) {
	m.defHeight = h
}

/**
 * @description:输出文本
 * @param {*gopdf.GoPdf} pdf
 * @param {string} text
 * @param {*} x
 * @param {float64} y
 * @param {*color.RGBA} rgb
 * @param {*Font} font
 * @return {*}
 */
func (m *PdfX) Default(rgb *color.RGBA, font *xfont.Font) *PdfX {
	if rgb != nil {
		m.SetTextColor(rgb.R, rgb.G, rgb.B)
	}

	if font != nil {
		if font.Size() > 0 {
			m.defHeight = float64(font.Height())
			m.SetFontSize(float64(font.Size()))
		}
		if font.Style != "" {
			m.SetFont(font.Name(), font.Style, font.Size())
		}
	}
	return m
}

func (m *PdfX) Text(x, y float64, text string) float64 {
	if x == 0 {
		x = m.MarginLeft()
	}
	if y > (m.pdfHight + m.defHeight) {
		m.AddPage()
		y = m.pdfTop
	}
	m.SetXY(x, y)
	m.GoPdf.Text(text)
	y += float64(m.defHeight) + 5 //行间距
	return y
}

/*
@desc 图片限制长度，到达一定长度添加新页
@param getX(写入pdf的X轴)、getY(写入pdf的Y轴)、getpdf(pdf对象)、buf(图片)
@return Y(返回pdfY的轴)
*/
func (m *PdfX) AddImage(x, y, width, hight float64, png []byte) (float64, error) {
	if x == 0 {
		x = m.MarginLeft()
	}
	if y+hight > m.pdfHight {
		m.AddPage()
		y = m.pdfTop
	}
	imgH1, err := gopdf.ImageHolderByBytes(png)
	if err != nil {
		return y, err
	}
	err = m.ImageByHolder(imgH1, 20, y, &gopdf.Rect{W: width, H: hight})
	if err != nil {
		return y, err
	}
	m.SetXY(x, y)
	y += hight + 10
	return y, nil
}
